package ch19

import (
	"errors"
	"time"
)

type Connection struct {
}

type ConnectionPool struct {
	bufferChannel chan *Connection
}

func NewConnectionPool(poolSize int)  *ConnectionPool{
	connectionPool := &ConnectionPool{}
	connectionPool.bufferChannel = make(chan *Connection, poolSize)
	for i:=0;i<poolSize;i++{
		connectionPool.bufferChannel <- new(Connection)
	}
	return connectionPool;
}

func (p *ConnectionPool) GetConnection(timeout time.Duration)  (*Connection,error){
	select {
	case result:=<-p.bufferChannel:
		return result,nil
	case <-time.After(timeout):
		return nil, errors.New("timeout")
	}
}

func (p *ConnectionPool) ReleaseConnection(connection *Connection)  error{
	select {
	case p.bufferChannel<-connection:
		return nil;
	default:
		return errors.New("overflow")

	}
}

